/**
 * @NApiVersion 2.x
 * @NScriptType Restlet
 * @NModuleScope SameAccount
 */
define(['N/http', 'N/https', 'N/record', 'N/search', 'N/runtime'],
/**
 * @param {http} http
 * @param {https} https
 * @param {record} record
 * @param {search} search
 */
function(http, https, record, search,runtime) {
   
   
    /**
     * Function called upon sending a GET request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.1
     */
    function doGet(requestParams) {

    }

    /**
     * Function called upon sending a PUT request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPut(requestBody) {

    }
   
    /**
     * Function called upon sending a POST request to the RESTlet.
     *
     * @param {string | Object} requestBody - The HTTP request body; request body will be passed into function as a string when request Content-Type is 'text/plain'
     * or parsed into an Object when request Content-Type is 'application/json' (in which case the body must be a valid JSON)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doPost(requestBody) {
    	
    	
    	
    	log.error({
			title : '请求正文.',
			details : 'requestBody: ' + JSON.stringify(requestBody)
		});
    	var resultJson = {
    			 "status": "300",
			     "errMessage": "",
    			 "data": ""
    	};
    	
		try {
			log.debug('123',requestBody.abc)
			log.debug('po',requestBody.reference)
			if(requestBody.reference != '' && requestBody.reference !=null){
				try{
					var podata = getpodata(requestBody.reference);
					log.debug('podata',podata)
					if(podata!= -1){
						resultJson.status = '300';
						resultJson.data = podata
					}else{
						resultJson.status = '900';
						resultJson.errMessage = '操作失败，不存在该收货单。';
					}
				}catch(e){
					resultJson.status = '900';
					resultJson.errMessage = '操作失败，原因：'+e.message;

					log.debug('resultJson',resultJson);
				}



				return resultJson;
				
				
			}else {
				resultJson.status = '900';
				resultJson.errorMessage = '操作失败，reference不可为空。';
				log.debug('resultJson',resultJson);

				return resultJson;
			}	
			
		} catch (e) {
			// TODO: handle exception
			resultJson.status = '900';
			resultJson.errorMessage = e.message;
			log.debug('e',e);
			log.debug('resultJson',resultJson);

			return resultJson;
		}
		
		
		

    }

    /**
     * Function called upon sending a DELETE request to the RESTlet.
     *
     * @param {Object} requestParams - Parameters from HTTP request URL; parameters will be passed into function as an Object (for all supported content types)
     * @returns {string | Object} HTTP response body; return string when request Content-Type is 'text/plain'; return Object when request Content-Type is 'application/json'
     * @since 2015.2
     */
    function doDelete(requestParams) {

    }

    function getpodata(grid){
		var filter = [];
		var column = [];
		var data = {};
		filter.push(search.createFilter({
			name: 'tranid',
			operator:search.Operator.IS,
			values:grid
		}))
		filter.push(search.createFilter({
			name: 'mainline',
			operator:search.Operator.IS,
			values:true
		}))

		column.push(search.createColumn({name:'internalid'}));
		column.push(search.createColumn({name:'createdfrom'}));
		column.push(search.createColumn({name:'custbody_item_sandanpipei'}));
		column.push(search.createColumn({name:'trandate'}));
		column.push(search.createColumn({name:'currency'}));
		column.push(search.createColumn({name:'entity'}));
		column.push(search.createColumn({name:'tranid'}));
		column.push(search.createColumn({name:'subsidiary'}));

		var irsearch = search.create({
			type:'itemreceipt',
			filters:filter,
			columns:column
		})

		var irresult = irsearch.run().getRange({start:0,end:5});
		if(irresult && irresult.length > 0){
			var irinternalid = irresult[0].getValue('internalid');
			// log.debug('pointernalid',irinternalid)
			// var irrecord = record.load({type:'itemreceipt',id:irinternalid});
			data.reference = irresult[0].getValue('tranid')
			data.Vendor = irresult[0].getValue('entity')
			var cf = irresult[0].getText('createdfrom');
			cf = cf.split(' ');
			cf = cf[cf.length-1];
			cf = cf.substring(1,cf.length);
			data.createdform = cf
			data.date = getDateString(irresult[0].getValue('trandate'))
			data.subsidiary = irresult[0].getValue('subsidiary')
			data.currency = irresult[0].getText('currency')
			var sandan = irresult[0].getValue('custbody_item_sandanpipei')
			if(sandan == true){
				sandan = 'T'
			}else{
				sandan = 'F'
			}
			data.sandan = sandan
			if(data.reference != grid){
				data = -1;
			}
		}else{
			data = -1;
		}
		return data;
	}
	function getDateString(offsethour){
		var now = new Date(offsethour);
		var moffset = now.getTimezoneOffset();
		var t  = new Date(now.getTime() + ((8 * 60 + moffset) * 60 * 1000));
		//var t = new Date(now.getTime() + (offsethour * 60 * 60 * 1000));
		var year = t.getFullYear();
		var month = t.getMonth() + 1;
		var day = t.getDate();
		var hour = t.getHours();
		var minute = t.getMinutes();
		var second = t.getSeconds();

		month = month < 10 ? '0' + month : month;
		day = day < 10 ? '0' + day : day;
		hour = hour < 10 ? '0' + hour : hour;
		minute = minute < 10 ? '0' + minute : minute;
		second = second < 10 ? '0' + second : second;

		return year + '/' + month + '/' + day;
	}


    return {
        'get': doGet,
        put: doPut,
        post: doPost,
        'delete': doDelete
    };
    
});
